//
//  JScendShopControllerViewController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/18.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JScendShopControllerViewController.h"
#import "UICollectionView+JCollectionView.h"
#import "JProductDetailController.h"
#import "JBaseCollectionViewCell.h"
#import "JProductSecindTypeView.h"
#import "JEmptyDataView.h" // 空数据展示
#define orderBykey @"orderBy" //默认为1，价格升序为2，降序为4
#define pageIndexkey @"pageIndex"
#define pageSizekey @"pageSize"

#define categoryIdkey @"categoryId" // 0
#define categoryLevelkey @"CategoryLevel" // 默认 1  如果点击全部分类 2

//CategoryId:"49"CategoryLevel:2CustomerId:"10004"UserId:"10004"orderBy:1pageIndex:1pageSize:10

@interface JScendShopControllerViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectView;
@property (nonatomic, strong) JProductSecindTypeView *listView;
@property (nonatomic, strong) JEmptyDataView *emptyView;

@property (nonatomic, strong) JProductTypeModel *selTypeModel;

@property (nonatomic, copy) NSArray *listArr;
@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, strong) JGetPageModel *pageModel;
@property (nonatomic, strong) NSMutableArray *btnArr;
@property (nonatomic, strong) UIView  *lineView;
@property (nonatomic, assign) NSInteger isDown; // 1 下， 2 上

@property (nonatomic, assign) NSInteger lestSelnum;
@property (nonatomic, strong) NSMutableDictionary *parameterDic;

@property (nonatomic, assign) BOOL isGetTypeList;

@end

@implementation JScendShopControllerViewController

- (JGetPageModel *)pageModel
{
    if (!_pageModel) {
        _pageModel = [JGetPageModel new];
        _pageModel.orderBy = 1;   //默认为1，价格升序为2，降序为4
        _pageModel.pageIndex = 1;
        _pageModel.pageSize = 10;
        
    }
    return _pageModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];
    
    self.titleLabel.text = self.typeModel.Name;
    self.leftButton.hidden = NO;
    self.rightButton.hidden = NO;
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
    [self.rightButton setImage:[UIImage imageNamed:@"shopcarsmall"] forState:UIControlStateNormal];
    self.selTypeModel = self.typeModel;
    
    _btnArr = [NSMutableArray array];
    _dataArr = [NSMutableArray array];
    _listArr = [NSMutableArray array];
    _parameterDic = [NSMutableDictionary dictionary];
    [_parameterDic setObject:@([GLOBALDATA userInfoModel].CustomerId) forKey:@"CustomerId"];
    [_parameterDic setObject:@([GLOBALDATA userInfoModel].CustomerId) forKey:@"UserId"];
    _isDown = 0;
    _isGetTypeList = YES;
    
    [self setTopBtnSelConfigView]; // 上方 按钮
    [self setConfigCollectView]; // 瀑布流数据
    [self setConfigEmptyView]; // 空数据展示
    [self setConfigListView]; // 商品全部分类 展示
    
}


- (void)setTopBtnSelConfigView {
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.contentView.width, 50)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:bottomView];
    
    NSArray *nameArr = @[@"销量",@"价格",@"全部分类"];
    CGFloat selbtnWidth = bottomView.width/3.0;
    
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        collectBtn.frame = CGRectMake(selbtnWidth * i , 0, selbtnWidth, 40);
        collectBtn.titleLabel.font = kFONT_TITLE(14);
        [collectBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        [collectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [collectBtn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        collectBtn.tag = 10 + i;
        
        [collectBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        collectBtn.selected = NO;
        if (i == 0) {
            collectBtn.selected = YES;
        }
        
        if (i == 1) {
            if (_isDown == 0) {
                [collectBtn setImage:[UIImage imageNamed:@"updown"] forState:UIControlStateNormal];
            }
            else if (_isDown == 1)
            {
                [collectBtn setImage:[UIImage imageNamed:@"upred"] forState:UIControlStateNormal];
            }
            else if (_isDown == 2)
            {
                [collectBtn setImage:[UIImage imageNamed:@"downred"] forState:UIControlStateNormal];
            }
            
            [collectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
            [collectBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 60, 0, 5)];
            
        }
        if (i == 2) {
            [collectBtn setImage:[UIImage imageNamed:@"down_1"] forState:UIControlStateNormal];
            
            [collectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
            [collectBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 93, 0, 5)];
        }
        
        [bottomView addSubview:collectBtn];
        [_btnArr addObject:collectBtn];
    }
}


- (void)setConfigCollectView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    _collectView = [UICollectionView initWithCollectionView:CGRectMake(0, 50, kWindowW, CGRectGetHeight(self.contentView.frame) - 50) withDelegate:self];
    
    //    __weak typeof(self) weakSelf = self;
    _collectView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (self.dataArr.count == self.pageModel.pageIndex * self.pageModel.pageSize) {
            self.pageModel.pageIndex += 1;
            [self loadProductListRequest];
            [_collectView.mj_footer endRefreshing];
        }
        else if (self.dataArr.count == 0)
        {
            [self loadProductListRequest];
            [_collectView.mj_footer endRefreshing];
        }
        else
        {
            [_collectView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
    
    [_collectView.mj_footer beginRefreshing];
    
    
    // 注册cell
    [self.collectView registerClass:[JBaseCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([JBaseCollectionViewCell class])];
    
    [self.contentView addSubview:_collectView];
    
}

- (void)setConfigListView {
    _listView = [[JProductSecindTypeView alloc]initWithFrame:CGRectMake(0, 50, self.collectView.width, self.contentView.height - 50)];
    _listView.hidden = YES;
    [self.contentView addSubview:_listView];
    [self.contentView bringSubviewToFront:_listView];
    
    __weak typeof(self) weakSelf = self;
    _listView.cancelBlock = ^{
        [weakSelf ProductTypeViewAnimation:NO];
        UIButton *btn = weakSelf.btnArr.lastObject;
        btn.selected = NO;
        
    };
    
    _listView.productTypeBlock = ^(JProductTypeModel *typeModel) {
        weakSelf.selTypeModel = typeModel;
        [weakSelf.dataArr removeAllObjects];
        weakSelf.pageModel.pageIndex = 1;
        [weakSelf loadProductListRequest];
        [weakSelf ProductTypeViewAnimation:NO];
        UIButton *btn = weakSelf.btnArr.lastObject;
        btn.selected = NO;
        [btn setTitle:typeModel.Name forState:UIControlStateNormal];
    };
}

- (void)setConfigEmptyView
{
    _emptyView = [[JEmptyDataView alloc]initWithFrame:CGRectMake(0, 50, self.contentView.width, self.contentView.height - 50)];
    _emptyView.hidden = YES;
    [self.contentView addSubview:_emptyView];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JBaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([JBaseCollectionViewCell class]) forIndexPath:indexPath];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (self.dataArr.count > indexPath.row) {
            cell.prodeutModel = self.dataArr[indexPath.row];
        }
        
    });
    
    return cell;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellwidth = (kWindowW - 15*3)/2.0;
    return (CGSize){cellwidth,260};
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(15, 15, 15, 15);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}

#pragma mark ---- UICollectionViewDelegate

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


// 选中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    JProductDetailController *detail = [[JProductDetailController alloc]init];
    detail.productModel = _dataArr[indexPath.row];
    detail.inputType = 1; // 表示非购物车进入商品详情
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)btnClick:(UIButton *)btn
{
    if (btn.tag == 12) {
        btn.selected = !btn.selected;
        [self ProductTypeViewAnimation:btn.selected];
        return;
    }
    else if (btn.tag == 11) {
        if (btn.tag == _lestSelnum) {
            if (_isDown == 1) {
                _isDown = 2 ;
            }
            else
            {
                _isDown = 1;
            }
        }
        else
        {
            _isDown = 1;
        }
        
        if (_isDown == 1) {
            [btn setImage:[UIImage imageNamed:@"upred"] forState:UIControlStateNormal];
        }
        else if(_isDown == 2)
        {
            [btn setImage:[UIImage imageNamed:@"downred"] forState:UIControlStateNormal];
        }
        
    }
    else if (btn.tag == 10)
    {
        
        if (btn.tag == _lestSelnum) {
            return;
        }
        
        _isDown = 0;
        UIButton *btnn = _btnArr[1];
        [btnn setImage:[UIImage imageNamed:@"updown"] forState:UIControlStateNormal];

    }
    
    for (UIButton *btn in self.btnArr) {
        btn.selected = NO;
    }
    btn.selected = YES;
    
    _lestSelnum = btn.tag;
    
    if (btn.tag == 10) {
        self.pageModel.orderBy = 1;
    }
    else
    {
        if (_isDown == 1) {
            self.pageModel.orderBy = 4;
            
        }
        else
        {
            self.pageModel.orderBy = 2;
            
        }
    }
    [self.dataArr removeAllObjects];
    self.pageModel.pageIndex = 1;
    [self loadProductListRequest];
    
}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonClick:(UIButton *)rightButton
{
    // 前往购物车
    JGoShopCarViewController;
}


- (void)loadProductListRequest
{
    [self setConfigRequestParameterMethod];
    
//    NSLog(@"parameterDic==%@",self.parameterDic);
    
    NSString *url = @"Products/GetProducts";
    [JNetManager getProductListRequestUrl:url
                           productListDic:self.parameterDic
                                  success:^(id response) {
                                      if (response) {
                                          
                                          [self.dataArr addObjectsFromArray:response];
                                          if (self.dataArr.count == 0) {
                                              self.emptyView.hidden = NO;
                                              self.collectView.hidden = YES;
                                          }
                                          else
                                          {
                                              self.emptyView.hidden = YES;
                                              self.collectView.hidden = NO;
                                              [self.collectView reloadData];
                                              if (_isGetTypeList) {
                                                  [self loadGetCategoriesByParentId];
                                                  _isGetTypeList = NO;
                                              }
                                          }
                                          
                                      }
                                  } failure:^(NSString *err) {
                                      [SVProgressHUD showErrorWithStatus:err];
                                      
                                  }];
}

- (void)setConfigRequestParameterMethod
{
    
    if ([self.parameterDic objectForKey:orderBykey]) {
        [self.parameterDic removeObjectForKey:orderBykey];
        [self.parameterDic setObject:@(self.pageModel.orderBy) forKey:orderBykey];
    }
    else
    {
        [self.parameterDic setObject:@(self.pageModel.orderBy) forKey:orderBykey];
    }
    
    if ([self.parameterDic objectForKey:pageIndexkey]) {
        [self.parameterDic removeObjectForKey:pageIndexkey];
        [self.parameterDic setObject:@(self.pageModel.pageIndex) forKey:pageIndexkey];
    }
    else
    {
        [self.parameterDic setObject:@(self.pageModel.pageIndex) forKey:pageIndexkey];
    }
    
    if ([self.parameterDic objectForKey:pageSizekey]) {
        [self.parameterDic removeObjectForKey:pageSizekey];
        [self.parameterDic setObject:@(self.pageModel.pageSize) forKey:pageSizekey];
    }
    else
    {
        [self.parameterDic setObject:@(self.pageModel.pageSize) forKey:pageSizekey];
    }
    
    if ([self.parameterDic objectForKey:categoryIdkey]) {
        [self.parameterDic removeObjectForKey:categoryIdkey];
        [self.parameterDic setObject:@(self.selTypeModel.Id) forKey:categoryIdkey];
    }
    else
    {
        [self.parameterDic setObject:@(self.selTypeModel.Id) forKey:categoryIdkey];
    }
    
    NSInteger level = 1;
    if (self.selTypeModel.Level == 0) {
        level = 2;
    }
    else {
        
    }
    
    if ([self.parameterDic objectForKey:categoryLevelkey]) {
        [self.parameterDic removeObjectForKey:categoryLevelkey];
        [self.parameterDic setObject:@(level) forKey:categoryLevelkey];
    }
    else
    {
        [self.parameterDic setObject:@(level) forKey:categoryLevelkey];
    }
    
}


/// 获取商品类型 请求
- (void)loadGetCategoriesByParentId
{
    NSString *url = @"Categories/GetCategoriesByParentId";
    [JNetManager getProductSecondRequestUrl:url
                           productTypeModel:self.selTypeModel
                                    success:^(id response) {
                                        if (response) {
                                            NSMutableArray *marr = response;
                                            JProductTypeModel *model = self.typeModel;
                                            model.Name = @"全部分类";
                                            [marr insertObject:model atIndex:0];
                                            
                                            self.listArr = marr;
                                            self.listView.dataArr = self.listArr;
                                        }
                                    } failure:^(NSString *err) {
                                        [SVProgressHUD showErrorWithStatus:err];
                                    }];
}

- (void)ProductTypeViewAnimation:(BOOL)isShow
{
    if (isShow) {
        _listView.hidden = NO;
        
        [UIView animateWithDuration:0.3 animations:^{
            
            if (_listArr.count > 0) {
                self.listView.tableView.frame = CGRectMake(100, 0, self.contentView.width - 100, self.contentView.height);
                
            }
        }];
    }
    else
    {
        [UIView animateWithDuration:0.3 animations:^{
            
            _listView.tableView.frame = CGRectMake(self.contentView.width, 0 , 0, 0);
            
            [self.listView setHidden:YES];
            // 延迟消失
            //            [self performSelector:@selector(typeViewCancel) withObject:nil afterDelay:0.3];
        }];
    }
}

//- (void)lineViewAnimation:(NSInteger)num
//{
//    
//    [UIView animateWithDuration:0.3 animations:^{
//        _lineView.frame = CGRectMake((self.contentView.width/2.0 - 30)/2.0 + num * self.contentView.width/2.0, _lineView.origin.y, _lineView.width, _lineView.height);
//    }];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
